import React, { Children, memo } from 'react';
import { Modal, Card, message } from 'antd';
import { connect } from 'react-redux';
import styles from './index.less';
import { findNodeById, randomString } from '@/utils';

function SelectComponentsPanel({ hideSelectCompPanel, project, saveNodeChange }: any) {
  const { isShowSelectCompPanel, componentList, currentCompId, pageConfig, currentPropName  } =
    project;
  const currentComponent: API.Node | undefined = findNodeById(
    pageConfig,
    currentCompId,
  );
  
  /**
   * 选择组件插入到当前选中的组件中
   * @param comp 当前选择的(要插入的)组件
   * @returns {void}
   */
  const handleSaveSelectedComponent = (comp: API.IMaterial) => {
    if (!currentComponent) return;
    const newComponent: API.Node = {
      type: 'node',
      id: randomString(),
      tag: comp.tag,
      props: {},
      style: {}
    };
    if (comp.default) {
      newComponent.children = comp.default.children;
      newComponent.props = comp.default.props || {};
    }
    const currentComponentPropValue = currentComponent[currentPropName];
    if (!currentComponentPropValue) 
      currentComponent[currentPropName] = [];
    
    if (typeof currentComponentPropValue === 'string')
    currentComponent[currentPropName] = [currentComponentPropValue];

    currentComponent[currentPropName].push(newComponent);
    saveNodeChange(currentComponent);
    // 关闭对话框
    hideSelectCompPanel();
    message.success('添加成功');
  };

  return (
    <Modal
      title="请选择组件"
      footer={null}
      visible={isShowSelectCompPanel}
      onCancel={hideSelectCompPanel}
      width={800}
    >
      <div className={styles.compsContent}>
        {componentList.map((comp: API.IMaterial) => (
          <Card
            hoverable
            className={styles.card}
            key={comp.id}
            bordered
            size="small"
            onClick={() => handleSaveSelectedComponent(comp)}
          >
            <div className={styles.imgContent}>
              <img src={comp.pic} alt="" className={styles.pic} />
            </div>
            <div className={styles.meta}>{comp.name}</div>
          </Card>
        ))}
      </div>
    </Modal>
  );
}

export default connect(({ project }: any) => ({ project }), {
  hideSelectCompPanel: () => ({ type: 'project/hideSelectCompPanel' }),
  saveNodeChange: (payload: { style: React.CSSProperties }) => ({
    type: 'project/saveNodeChange',
    payload,
  }),
  save: (payload: any) => ({ type: 'project/save', payload }),
})(memo(SelectComponentsPanel));
